from fastapi import APIRouter, Query, Request, Depends
from sqlalchemy.orm import Session
from typing import List
from utils.response import success, fail, tableinfo
from utils.request import PageInfo, QueryWrapper
from utils.database import get_db
from app.model import UserModel
from app.schema import UserData, ResetPassData, SetRoleData
from utils.permission import has_permission

userController = APIRouter()

@userController.post("/add")
async def add_data(data: UserData, db: Session = Depends(get_db)):
    """
    增加用户
    """
    try:
        r = UserModel.insert(db, data)
        return success("添加成功")
    except Exception as e:
        return fail("添加失败："+str(e))

@userController.post("/edit")   
async def edit_data(data: UserData, db: Session = Depends(get_db)):
    """
    修改用户
    """
    try:
        row = data.dict(exclude_unset=True)
        r = UserModel.edit(db, row)
        return success("修改成功")
    except Exception as e:
        return fail("修改失败："+str(e))
    
@userController.post("/delete")   
async def delete_data(ids:List[int], db: Session = Depends(get_db)):
    """
    修改用户
    """
    try:
        r = UserModel.delete(db, ids)
        return success("删除成功")
    except Exception as e:
        return fail("删除失败："+str(e))

@userController.get("/selectoptions")
async def get_select(db = Depends(get_db)):
    options = UserModel.get_select_options(db)
    return success("操作成功", options)


@userController.get("/get")
async def get_one(id:int,  db: Session = Depends(get_db)):
    row = UserModel.get_by_id(db, id)
    return success("操作成功", row)


@userController.get("/menus")
async def get_one(id:int,  db: Session = Depends(get_db)):
    row = UserModel.get_role_menus(db, id)

    return success("操作成功",[v.menu_id for v in row])

# 2	管理员
# 3	教务员
# 4	系主任
# 5	教师

@userController.get("/page")
@has_permission("教务员")
async def get_page( 
    req: Request,
    page:int=Query(default=1), 
    limit:int=Query(default=10), 
    filter:str=Query(default='{}'), 
    db: Session = Depends(get_db)
):
    page  = PageInfo(page, limit)
    where = QueryWrapper.build_query_wrapper(filter)
    total, rows = UserModel.get_page(db, where, page)
    return tableinfo("查询成功", total, rows)

@userController.post("/passwd")   
async def reset_password( data:ResetPassData, db: Session = Depends(get_db)):
    """
    修改用户
    """
    UserModel.reset_password(db, data.user_id, data.password)
    return success("操作成功")
    
@userController.get("/getroles")   
async def get_user_roles( id: int, db: Session = Depends(get_db)):
    """
    修改用户
    """
    return success("操作成功", UserModel.get_user_roles(db, id))

@userController.post("/setroles")   
async def reset_password( data:SetRoleData, db: Session = Depends(get_db)):
    """
    修改用户
    """
    UserModel.set_user_roles(db, data.user_id, data.roleIds)
    return success("操作成功")

